package com.mxx.qh.dialog;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.mxx.qh.R;
import com.mxx.qh.config.NetUrlConfig;
import com.mxx.qh.network.RequestEnum;
import com.mxx.qh.network.RetrofitHelper;
import com.mxx.qh.network.StringObserver;
import com.mxx.qh.response.BaseResponse;
import com.mxx.qh.response.GradeResponse;
import com.mxx.qh.response.QrCodeResponse;
import com.yp.loading.base.BaseDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * @ClassName: TokenEmptyDialog
 * @Description: 海报收徒
 * @Author: ljf89 (刘江飞)
 * @Date: 2021/1/15-- 18:10
 * @Email: 642371742@qq.com
 */
public class ResultDialog extends BaseDialog {
    private FrameLayout fl_result1;
    private TextView tv_score1;
    private TextView tv_pupil_devote1;
    private TextView tv_disciple_devote1;
    private TextView tv_task_commission1;
    private TextView tv_vip_income1;
    private ImageView iv_qr_code1;

    private FrameLayout fl_result2;
    private TextView tv_score2;
    private TextView tv_pupil_devote2;
    private TextView tv_disciple_devote2;
    private TextView tv_task_commission2;
    private TextView tv_vip_income2;
    private ImageView iv_qr_code2;

    private FrameLayout fl_result3;
    private TextView tv_score3;
    private TextView tv_pupil_devote3;
    private TextView tv_disciple_devote3;
    private TextView tv_task_commission3;
    private TextView tv_vip_income3;
    private ImageView iv_qr_code3;

    private TextView tv_cancel;
    private TextView tv_exchange;
    private TextView tv_save;


    private int click_count = 1;
    private String qr_code_url;
    private GradeResponse gradeResponse;

    @Override
    public boolean isCancelable() {
        return false;
    }

    @Override
    protected boolean isCancelOutside() {
        return false;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.dialog_result;
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar
                .with(this)
                .fitsSystemWindows(false)
                .statusBarColor(android.R.color.transparent)
                .statusBarDarkFont(true)
                .init();
        fl_result1 = mRootView.findViewById(R.id.fl_result1);
        tv_score1 = mRootView.findViewById(R.id.tv_score1);
        tv_pupil_devote1 = mRootView.findViewById(R.id.tv_pupil_devote1);
        tv_disciple_devote1 = mRootView.findViewById(R.id.tv_disciple_devote1);
        tv_task_commission1 = mRootView.findViewById(R.id.tv_task_commission1);
        tv_vip_income1 = mRootView.findViewById(R.id.tv_vip_income1);
        iv_qr_code1 = mRootView.findViewById(R.id.iv_qr_code1);

        fl_result2 = mRootView.findViewById(R.id.fl_result2);
        tv_score2 = mRootView.findViewById(R.id.tv_score2);
        tv_pupil_devote2 = mRootView.findViewById(R.id.tv_pupil_devote2);
        tv_disciple_devote2 = mRootView.findViewById(R.id.tv_disciple_devote2);
        tv_task_commission2 = mRootView.findViewById(R.id.tv_task_commission2);
        tv_vip_income2 = mRootView.findViewById(R.id.tv_vip_income2);
        iv_qr_code2 = mRootView.findViewById(R.id.iv_qr_code2);

        fl_result3 = mRootView.findViewById(R.id.fl_result3);
        tv_score3 = mRootView.findViewById(R.id.tv_score3);
        tv_pupil_devote3 = mRootView.findViewById(R.id.tv_pupil_devote3);
        tv_disciple_devote3 = mRootView.findViewById(R.id.tv_disciple_devote3);
        tv_task_commission3 = mRootView.findViewById(R.id.tv_task_commission3);
        tv_vip_income3 = mRootView.findViewById(R.id.tv_vip_income3);
        iv_qr_code3 = mRootView.findViewById(R.id.iv_qr_code3);

        tv_cancel = mRootView.findViewById(R.id.tv_cancel);
        tv_exchange = mRootView.findViewById(R.id.tv_exchange);
        tv_save = mRootView.findViewById(R.id.tv_save);


        allGradeContainsGone();
        setGradeContainsVisible(click_count);
    }

    private void allGradeContainsGone() {
        fl_result1.setVisibility(View.GONE);
        fl_result2.setVisibility(View.GONE);
        fl_result3.setVisibility(View.GONE);
    }

    private void setGradeContainsVisible(int clickCount) {
        if (clickCount % 3 == 1) {
            fl_result1.setVisibility(View.VISIBLE);
        }
        if (clickCount % 3 == 2) {
            fl_result2.setVisibility(View.VISIBLE);
        }
        if (clickCount % 3 == 0) {
            fl_result3.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        loadQrCode();
    }

    private void loadQrCode() {
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("user/qr")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        qr_code_url = getQrCodeUrl(json);
                        loadQrCode(click_count);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private String getQrCodeUrl(String json) {
        Gson gson = new Gson().newBuilder().create();
        if (json == null || json.isEmpty()) {
            return null;
        }
        BaseResponse<QrCodeResponse> response = gson.fromJson(json, new TypeToken<BaseResponse<QrCodeResponse>>() {
        }.getType());
        if (response == null) {
            return null;
        }
        QrCodeResponse qrCodeResponse = gson.fromJson(gson.toJson(response.data), new TypeToken<QrCodeResponse>() {
        }.getType());
        if (qrCodeResponse.url_qr == null) {
            return null;
        }
        return qrCodeResponse.url_qr;
    }

    private void loadQrCode(int clickCount) {
        if (qr_code_url != null && !qr_code_url.isEmpty()) {
            new Thread(() -> Glide.with(mActivity)
                    .asBitmap()
                    .load(qr_code_url)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            mActivity.runOnUiThread(() -> {
                                if (clickCount % 3 == 1) {
                                    iv_qr_code1.setImageBitmap(resource);
                                }
                                if (clickCount % 3 == 2) {
                                    iv_qr_code2.setImageBitmap(resource);
                                }
                                if (clickCount % 3 == 0) {
                                    iv_qr_code3.setImageBitmap(resource);
                                }

                            });
                            loadGrade();
                        }
                    })).start();
        }
    }

    private void loadGrade() {
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("grade")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        gradeResponse = getGrade(json);
                        loadGrade(click_count);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private GradeResponse getGrade(String json) {
        Gson gson = new Gson().newBuilder().create();
        if (json == null || json.isEmpty()) {
            return null;
        }
        BaseResponse<GradeResponse> response = gson.fromJson(json, new TypeToken<BaseResponse<GradeResponse>>() {
        }.getType());
        if (response == null) {
            return null;
        }
        return gson.fromJson(gson.toJson(response.data), new TypeToken<GradeResponse>() {
        }.getType());
    }

    private void loadGrade(int clickCount) {
        if (gradeResponse == null) {
            return;
        }
        String total_amount = gradeResponse.total_amount;
        if (total_amount != null) {
            if (clickCount % 3 == 1) {
                tv_score1.setText(total_amount);
            }
            if (clickCount % 3 == 2) {
                tv_score2.setText(total_amount);
            }
            if (clickCount % 3 == 0) {
                tv_score3.setText(total_amount);
            }
        }
        String prent_amount = gradeResponse.prent_amount;
        if (prent_amount != null) {

            if (clickCount % 3 == 1) {
                tv_pupil_devote1.setText(prent_amount);
            }
            if (clickCount % 3 == 2) {
                tv_pupil_devote2.setText(prent_amount);
            }
            if (clickCount % 3 == 0) {
                tv_pupil_devote3.setText(prent_amount);
            }

        }
        String disciple_amount = gradeResponse.disciple_amount;
        if (disciple_amount != null) {
            if (clickCount % 3 == 1) {
                tv_disciple_devote1.setText(disciple_amount);
            }
            if (clickCount % 3 == 2) {
                tv_disciple_devote2.setText(disciple_amount);
            }
            if (clickCount % 3 == 0) {
                tv_disciple_devote3.setText(disciple_amount);
            }


        }
        String task_amount = gradeResponse.task_amount;
        if (task_amount != null) {
            if (clickCount % 3 == 1) {
                tv_task_commission1.setText(task_amount);
            }
            if (clickCount % 3 == 2) {
                tv_task_commission2.setText(task_amount);
            }
            if (clickCount % 3 == 0) {
                tv_task_commission3.setText(task_amount);
            }

        }
        String member_amount = gradeResponse.member_amount;
        if (member_amount != null) {
            if (clickCount % 3 == 1) {
                tv_vip_income1.setText(member_amount);
            }
            if (clickCount % 3 == 2) {
                tv_vip_income2.setText(member_amount);
            }
            if (clickCount % 3 == 0) {
                tv_vip_income3.setText(member_amount);
            }
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        tv_cancel.setOnClickListener(this);
        tv_exchange.setOnClickListener(this);
        tv_save.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_cancel) {
            dismiss();
        }
        if (v.getId() == R.id.tv_exchange) {
            click_count++;
            allGradeContainsGone();
            setGradeContainsVisible(click_count);
            loadQrCode(click_count);
            loadGrade(click_count);
        }
        if (v.getId() == R.id.tv_save) {
            saveByClickCount(click_count);
        }
    }

    private void saveByClickCount(int click_count) {
        new Thread(() -> {
            FrameLayout targetView = getTargetView(click_count);
            targetView.buildDrawingCache();
            Bitmap bitmap = targetView.getDrawingCache();
            String fileName = getFileName();
            saveBitmap(mActivity, bitmap, fileName);
            mActivity.runOnUiThread(this::dismiss);
        }).start();

    }

    private FrameLayout getTargetView(int clickCount) {
        if (clickCount % 3 == 1) {
            return fl_result1;
        }
        if (clickCount % 3 == 2) {
            return fl_result2;
        }
        if (clickCount % 3 == 0) {
            return fl_result3;
        }
        return fl_result1;
    }

    private String getFileName() {
        Calendar cal = Calendar.getInstance();
        //当前年
        int year = cal.get(Calendar.YEAR);
        //当前月
        int month = (cal.get(Calendar.MONTH)) + 1;
        //当前月的第几天：即当前日
        int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
        //当前时：HOUR_OF_DAY-24小时制；HOUR-12小时制
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        //当前分
        int minute = cal.get(Calendar.MINUTE);
        //当前秒
        int second = cal.get(Calendar.SECOND);
        String time = year + ""
                + month + ""
                + day_of_month + ""
                + hour + ""
                + minute + ""
                + second;

        return time + ".jpg";
    }

    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Context context, Bitmap bitmap, String bitName) {
        if (bitmap == null) {
            mActivity.runOnUiThread(() -> Toast.makeText(mActivity, "图片资源为空", Toast.LENGTH_SHORT).show());
            return;
        }
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            Log.v("qwe", "002");
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        mActivity.runOnUiThread(() -> Toast.makeText(mActivity, "保存图片成功", Toast.LENGTH_SHORT).show());
    }
}
